const express = require('express')
const router = express.Router()

const NavModel = require('../../model/navModel')
const { getUnix } = require('../../model/tools')

// const tools = require('../../model/tools')
// const upload = tools.multer()

router.get('/', async (req, res) => {
  let result = await NavModel.find({}).sort({sort: 1});
  res.render('admin/nav/index', {
    list: result
  })
})

router.get('/add', (req, res) => {
  res.render('admin/nav/add', {})
  // res.send("增加导航")
})

router.get('/delete', function(req, res) {
  var _id = req.query.id
  NavModel.deleteOne({_id}, function(err, data) {
    if(err) {
      console.log(err)
      res.send({
        code: 404,
        msg: '失败'
      })
      return;
    }
    console.log(data)
    if(data && data.deletedCount > 0) {
      res.send({
        code: 200,
        msg: '成功'
      })
    } else {
      res.send({
        code: 404,
        msg: '失败'
      })
    }
  })
})

router.get('/edit', async function (req, res) {
  // 获取管理员数据
  var id = req.query.id
  let result = await NavModel.find({'_id': id});
  if(result.length > 0) {
    res.render('admin/nav/edit', {
      list: result[0]
    })
  } else {
    res.redirect('/admin/nav')
  }
})

router.post('/doAdd', async (req, res) => {

  const nav = new NavModel(Object.assign(req.body, {
    create_time: getUnix()
  }))

  let result = await nav.save()
  if(result) {
   res.render('admin/public/success', {
    redirectUrl: '/admin/nav',
    message: '添加成功'
  })
  } else {
    res.render('admin/public/error', {
      redirectUrl: '/admin/nav/add',
      message: '添加失败'
    })
  }
})

// router.post('/doAdd', upload.single('pic'), (req, res) => {
//   // 获取表单传过来的数据
//   // res.send("执行增加：" + req.body.title + '-' + req.body.desc)

//   res.send({
//     body: req.body, 
//     file: req.file
//   })
// })

router.post('/doEdit', async (req, res) => {
  // 1. 获取表单提交的数据
  const _id = req.body.id
  const title = req.body.title
  const link = req.body.link
  const position = req.body.position
  const is_opennew = req.body.is_opennew
  const status = req.body.status
  const sort = req.body.sort

  // 2. 验证数据是否合法
  let result = await NavModel.find({_id})
  if(result && result.length > 0) {
    // 4. 执行修改操作
    var user = await NavModel.updateOne({_id}, 
      {
        title,
        link, position,
        is_opennew,
        status,
        sort,
        modify_time: getUnix()
      })
    if(user.modifiedCount > 0) {
      res.render('admin/public/success', {
        redirectUrl: '/admin/nav',
        message: '成功'
      })
    } else {
      res.render('admin/public/error', {
        redirectUrl: '/admin/nav/edit?id=' + _id,
        message: '失败'
      })
    }
  } else {
    res.render('admin/public/error', {
      redirectUrl: '/admin/nav/edit?id=' + _id,
      message: '失败'
    })
  }
})

module.exports = router
